package com.eric.husky.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Service
public class FileService {

	@Value("${filepath}")
	private String filepath;

	public String upload(MultipartFile file) throws IOException {
		// 获取原文件名
		String fileName = file.getOriginalFilename();
//		String[] arr = fileName.split("\\.");
//		String prefix = arr[arr.length - 1];
//		Boolean res = imageTypeList.contains(prefix);
//		String path;
//
//		if(res) {
//			path = "C:\\Users\\36484\\Desktop\\image";
//		} else {
//			path = "C:\\Users\\36484\\Desktop\\file";
//		}

		File filePath = new File(filepath, fileName);
		// 如果文件目录不存在，创建目录
		if (!filePath.getParentFile().exists()) {
			filePath.getParentFile().mkdirs();
		}
		// 写入文件
		file.transferTo(filePath);
		return filepath +"\\"+ fileName;
	}


	public void download(HttpServletResponse response, String downloadFilePath) {
		String[] arr = downloadFilePath.split("\\.");
		String fileName = arr[arr.length - 2] + "." + arr[arr.length - 1];//被下载文件的名称
		File file = new File(downloadFilePath);
		if (file.exists()) {
			response.setContentType("application/force-download");// 设置强制下载不打开            
			response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
			byte[] buffer = new byte[1024];
			FileInputStream fis = null;
			BufferedInputStream bis = null;
			try {
				fis = new FileInputStream(file);
				bis = new BufferedInputStream(fis);
				OutputStream outputStream = response.getOutputStream();
				int i = bis.read(buffer);
				while (i != -1) {
					outputStream.write(buffer, 0, i);
					i = bis.read(buffer);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (bis != null) {
					try {
						bis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (fis != null) {
					try {
						fis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}